package com.offcn.seckill.consumer;

import com.alibaba.fastjson.JSON;
import com.offcn.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 秒杀订单支付消息侦听器
 *
 * @author 秋林
 * @date 2022/10/21 17:04:13
 */

@Component
@RabbitListener(queues = "${mq.pay.queue.seckillorder}")
public class SeckillOrderPayMessageListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 监听消费消息
     */
    public void consumeMessage(@Payload String message) {
        //将信息转为Map对象
        Map<Spring, String> resultMap = JSON.parseObject(message, Map.class);
        System.out.println("监听到的信息： " + resultMap);

        //获取交易状态
        String trade_status = resultMap.get("trade_status");

        //判断交易状态是否成功
        if (!StringUtils.isEmpty(trade_status) && trade_status.equalsIgnoreCase("TRADE_SUCCESS")) {
            String body = resultMap.get("body");

            HashMap<String, String> bodyMap = new HashMap<>();

            if (!StringUtils.isEmpty(body)) {
                String[] splits = body.split("&");

                for (String split : splits) {
                    String[] vs = split.split("=");
                    bodyMap.put(vs[0], vs[1]);
                }
            }
            seckillOrderService.updatePayStatus(resultMap.get("out_trade_no"), resultMap.get("trade_no"), bodyMap.get("username"));
        } else {
            //支付失败，删除订单
            seckillOrderService.closeOrder(resultMap.get("username"));
        }
    }
}
